import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.File
import java.io.FileInputStream
import java.lang.Exception
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import kotlin.coroutines.resume


object ZipUtil {

    suspend fun unzip(zipFileName: String, outputDirectory: String) =
        suspendCancellableCoroutine<Boolean> { continuation ->
            var zipEntry: ZipEntry? = null
            var fileName = ""
            try {
                FileInputStream(zipFileName).use { fis ->
                    ZipInputStream(fis).use { zis ->
                        while (zis.nextEntry?.also { entry ->
                                zipEntry = entry
                            } != null) {
                            fileName = zipEntry!!.name
                            if (zipEntry!!.isDirectory) {
                                fileName = fileName.substring(0, fileName.length - 1)
                                val dir = File(outputDirectory + File.separator + fileName)
                                dir.mkdirs()
                            } else {
                                val file = File(outputDirectory + File.separator + fileName)
                                file.createNewFile()
                                file.writeBytes(zis.readBytes())
                            }
                        }
                        continuation.resume(true)
                    }
                }
            } catch (e: Exception) {
                continuation.resume(false)
            }
        }
}